$(document).ready(function() {
	SB.ReceivedBillModel = Backbone.Model.extend({
		
	});
	
	SB.ReceivedBillCollection = Backbone.Collection.extend({
		model: SB.ReceivedBillModel
	});
	
	SB.receivedBillCollection = new SB.ReceivedBillCollection();

	SB.NoBillReceivedView = Backbone.View.extend({
		className : "papers",
		template : _.template($('#no-bill-received-tpl').html()),
		
		initialize : function() {
			_.bindAll(this, 'render');

		},

		render : function() {
			$(this.el).html(this.template());
			return this;
		}
	});
	
	SB.ReceivedBillView = Backbone.View.extend({
		className : "papers",
		template: _.template($('#received-bill-tpl').html()),
		initialize : function() {
			_.bindAll(this, 'render', 'markPaid');
			this.model.on('change', this.render);
		},
		
		events: {
			'click #mark-paid': "markPaid",
		},

		render : function() {
			$(this.el).html(this.template(this.model.toJSON()));
			console.log(this.model.get('paid'));
			if (this.model.get('paid') == true) {
				$(this.el).removeClass('unpaid');
				$(this.el).addClass('paid');
			}
			else {
				$(this.el).removeClass('paid');
				$(this.el).addClass("unpaid");
			}
			return this;
		},
		
		markPaid: function() {
			var url = '/api/friend-bill/update/';
			payload = {};
			payload.friend_bill_id = this.model.get('id');
			payload.paid = "paid";
			payload.reply = this.$('#reply').val();
			var $this = this;
			$.post(url, payload, function(data) {
				$this.model.set(JSON.parse(data));
				SB.requestedBills = SB.receivedBillCollection.toJSON();
			});
		}
	});
	
	SB.ReceivedBillCollectionView = Backbone.View.extend({
		className : "span7 new-bill",
		initialize : function() {
			_.bindAll(this, 'render', 'addOne', 'removeOne');

			// Reset view when emails changes
			SB.receivedBillCollection.on('reset', this.render);
			SB.receivedBillCollection.on('add', this.addOne);
			SB.receivedBillCollection.on('remove', this.removeOne);
		},

		render : function() {
			$(this.el).html('');
			$this = this;
			_.each(SB.receivedBillCollection.models, function(model) {
				$this.addOne(model);
			});
			
			if (SB.receivedBillCollection.length == 0) {
				var noBillReceivedView = VM.reuseView("noBillReceivedView", function(){
					return new SB.NoBillReceivedView();
				});
				$(this.el).append(noBillReceivedView.render().el);
			}
			
			return this;
		},

		addOne : function(model) {
			var receivedBillView = new SB.ReceivedBillView({
				model : model
			});
			$(this.el).append(receivedBillView.render().el);
			$(this.el).append('<p></p><br/>');
		},

		// Remove
		removeOne : function(model) {
		}		
	});
});
